/**
 * Copyright (c) 2010-2011 julewa.com.  
 * All rights reserved. 
 * 
 * @author Huang Benhua
 * @date 2011-7-20
 * 
**/
package com.julewa.loading;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import com.julewa.Texts;

//TODO 这里的实现暂且不考虑国际化
public class TextsImpl implements Texts{
	
	private Map<String, String> texts = 
		Collections.synchronizedMap(new HashMap<String, String>());
	private Map<String, String> labels = 
		Collections.synchronizedMap(new HashMap<String, String>());

	public void putText(String key, String value){
		texts.put(key, value);
	}
	
	public void putLabel(String key, String value){
		labels.put(key, value);
	}
	
	@Override
	public String getText(String key) {
		return texts.get(key);
	}

	@Override
	public String getText(String key, Object... args) {
		String str = texts.get(key);
		if(str == null)return null;
		return String.format(str, args);
	}

	@Override
	public String getLabel(String key) {
		return labels.get(key);
	}

	@Override
	public String findLabel(String prefix, String key) {
		prefix = labels.get(prefix + "." + key);
		if(prefix != null)return prefix;
		prefix = labels.get(key);
		if(prefix != null)return prefix;
		return key;
	}

	@Override
	public String findLabel(String f) {
		String txt = getLabel(f);
		if(txt != null)return txt;
		int idx = f.lastIndexOf('.');
		if(idx < 0)return f;
		txt = getLabel(f.substring(idx + 1));
		if(txt == null)return f;
		return txt; 
	}
	
	//TODO 需要改成可配置的
	private static MessageDigest MD = null;
	private static final String MDKEY = "qekfrhtor/pqlujehjedpakjl;fjepw;lkr;sork;wepotkit6irw rujriujtpwdlgjixdhei";
	static{
		try {
			MD = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e){
			e.printStackTrace();
		}
	}
	private MessageDigest _getMD5(){
		try {
			return (MessageDigest)MD.clone();
		} catch (CloneNotSupportedException e) { 
			e.printStackTrace();
			return null;
		}
	}
    public final String encodeMD5(String text){
        if("".equals(text))return "";
        MessageDigest md = _getMD5();
        if(md == null)return text;
        md.update(new StringBuffer(text).append(MDKEY).toString().getBytes());
        char code[] = new String(md.digest()).toCharArray();
        long cnt = 0;
        for(char c: code) cnt += c;
        return "" + cnt;
    }

}
